package nccloud.web.pu.buyingreq.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nc.itf.uap.pf.IPfExchangeService;
import nc.pubitf.pu.m422x.pu.m20.IQuery422xFor20;
import nc.ui.querytemplate.querytree.IQueryScheme;
import nc.vo.pu.m20.entity.PraybillSupplierVO;
import nc.vo.pu.m20.entity.PraybillVO;
import nc.vo.pu.m422x.entity.StoreReqAppHeaderVO;
import nc.vo.pu.m422x.entity.StoreReqAppItemVO;
import nc.vo.pu.m422x.entity.StoreReqAppVO;
import nc.vo.pu.pub.util.BillHelper;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.pubapp.pattern.pub.SqlBuilder;
import nc.vo.pubapp.query2.sql.process.QuerySchemeProcessor;
import nc.vo.scmpub.res.billtype.POBillType;
import nc.vo.scmpub.util.TransferSortUtil;
import nccloud.dto.baseapp.querytree.dataformat.Condition;
import nccloud.dto.baseapp.querytree.dataformat.QueryCondition;
import nccloud.dto.baseapp.querytree.dataformat.QueryTreeFormatVO;
import nccloud.dto.baseapp.querytree.dataformat.Value;
import nccloud.dto.pu.buyingreq.entity.BaseVariable;
import nccloud.dto.pu.buyingreq.entity.PkTsParamsVO;
import nccloud.dto.pu.buyingreq.entity.TransferData;
import nccloud.dto.pu.buyingreq.entity.TransferInfo;
import nccloud.dto.scmpub.pub.utils.SCMRowNoUtils;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.core.json.IJson;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.json.JsonFactory;
import nccloud.framework.web.ui.pattern.billcard.BillCard;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCard;
import nccloud.framework.web.ui.pattern.extbillcard.ExtBillCardOperator;
import nccloud.pubitf.platform.query.INCCloudQueryService;
import nccloud.web.pu.buyingreq.util.BuyingReqScaleUtil;

public class TransferAction implements ICommonAction {
	public Object doAction(IRequest request) {
		ExtBillCard[] cards = null;
		try {
			String read = request.read();
			IJson json = JsonFactory.create();

			TransferInfo info = (TransferInfo) json.fromJson(read, TransferInfo.class);

			Map<String, UFDateTime> idTsMap = new HashMap<String, UFDateTime>();

			Map<String, UFDateTime> idTsMapBody = new HashMap<String, UFDateTime>();
			TransferData[] datas = info.getData();
			Set<String> bodyPks = new HashSet<String>();
			if (datas != null) {
				for (TransferData data : datas) {
					PkTsParamsVO head = data.getHead();
					if (head != null) {
						idTsMap.put(head.getPk(), new UFDateTime(head.getTs()));
					}
					PkTsParamsVO[] bodys = data.getBodys();
					if (bodys != null) {
						for (PkTsParamsVO body : bodys) {
							idTsMap.put(body.getPk(), new UFDateTime(body.getTs()));
							idTsMapBody.put(body.getPk(), new UFDateTime(body.getTs()));
							bodyPks.add(body.getPk());
						}
					}
				}
			}

			IQueryScheme scheme = getQueryScheme(info, bodyPks);
			IQuery422xFor20 query = (IQuery422xFor20) ServiceLocator.find(IQuery422xFor20.class);

			StoreReqAppVO[] sorceVOs = query.queryStoreReqApps(scheme);

			if (sorceVOs != null) {
				for (StoreReqAppVO vo : sorceVOs) {
					StoreReqAppHeaderVO head = vo.getHVO();
					head.setTs((UFDateTime) idTsMap.get(head.getPk_storereq()));
					StoreReqAppItemVO[] items = vo.getBVO();
					if (items != null) {
						for (StoreReqAppItemVO item : items) {
							if (idTsMap.get(item.getPk_storereq_b()) != null) {
								item.setTs((UFDateTime) idTsMap.get(item.getPk_storereq_b()));
							}
						}
					}
				}
			}

			IPfExchangeService service = (IPfExchangeService) ServiceLocator.find(IPfExchangeService.class);
			PraybillVO[] vos = (PraybillVO[]) service.runChangeDataAry(POBillType.MRBill.getCode(),
					POBillType.PrayBill.getCode(), sorceVOs, null);

			vos = (PraybillVO[]) (new TransferSortUtil("vsourcerowno", "vsourcecode")).sort(vos);
			ExtBillCardOperator extOperator = new ExtBillCardOperator(info.getTempletId(), info.getPagecode());
			BillCardOperator operator = new BillCardOperator(info.getTempletId(), info.getPagecode());
			if (vos != null && vos.length > 0) {
				cards = new ExtBillCard[vos.length];
				for (int i = 0; i < vos.length; i++) {
					int[] rows = getItemRows(vos[i]);
					PraybillSupplierVO[] supplierVOs = new PraybillSupplierVO[1];
					supplierVOs[0] = new PraybillSupplierVO();
					vos[i].setSupplierVO(supplierVOs);
					SCMRowNoUtils.setMultiSelectRowNo(vos[i].getBVO(), rows);
					ExtBillCard extBillCard = extOperator.toCard(vos[i]);
					BillCard billCard = operator.toCard(vos[i]);
					afterProcess(billCard);
					cards[i] = extBillCard;
				}
			}
		} catch (Exception e) {
			ExceptionUtils.wrapException(e);
		}

		return cards;
	}

	public void afterProcess(BillCard card) {
		BuyingReqScaleUtil buyUtil = new BuyingReqScaleUtil();
		buyUtil.processBillCard(card, false);
	}

	private IQueryScheme getQueryScheme(TransferInfo queryInfo, Set<String> bodyPks) {
		BaseVariable bv = new BaseVariable();
		QueryTreeFormatVO qtf = new QueryTreeFormatVO();
		qtf.setQuerytype(bv.getTree());
		qtf.setOid(queryInfo.getOid());
		qtf.setPageInfo(null);
		qtf.setQueryAreaCode(queryInfo.getQueryAreaCode());
		qtf.setPageCode(queryInfo.getPagecode());
		QueryCondition querycondition = new QueryCondition();
		List<Condition> conditions = new ArrayList<Condition>();
		Condition condition = new Condition();
		condition.setOprtype(bv.getEqual());
		condition.setField(bv.getPk_storereq_bb());
		StringBuilder sb = new StringBuilder();
		for (String pk : bodyPks) {
			sb.append(pk).append(bv.getComma());
		}
		if (sb.length() > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		Value value = new Value();
		value.setFirstvalue(sb.toString());
		condition.setValue(value);
		condition.setLogic("and");
		conditions.add(condition);
		querycondition.setConditions(conditions);
		querycondition.setLogic("and");
		qtf.setQuerycondition(querycondition);

		INCCloudQueryService queryutil = (INCCloudQueryService) ServiceLocator.find(INCCloudQueryService.class);
		IQueryScheme queryScheme = queryutil.convertCondition(qtf);
		QuerySchemeProcessor processor = new QuerySchemeProcessor(queryScheme);
		String table = processor.getTableAliasOfAttribute("pk_storereq_b");
		SqlBuilder sqlb = new SqlBuilder();
		sqlb.append(" and ");
		sqlb.append("po_storereq_b1.pk_storereq_b", (String[]) bodyPks.toArray(new String[bodyPks.size()]));

		processor.appendWhere(sqlb.toString());

		return queryScheme;
	}

	private int[] getItemRows(PraybillVO aggVO) {
		BillHelper<PraybillVO> helper = new BillHelper<PraybillVO>(aggVO);
		int[] trows = new int[aggVO.getBVO().length];
		List<Integer> lists = new ArrayList<Integer>();
		for (int i = 0; i < trows.length; i++) {
			Object object = helper.getBodyValue(i, "pk_material");
			if (object != null && !object.toString().equals("null")) {
				lists.add(Integer.valueOf(i));
			}
		}
		int[] rows = new int[lists.size()];
		for (int n = 0; n < lists.size(); n++) {
			rows[n] = ((Integer) lists.get(n)).intValue();
		}
		return rows;
	}
}
